/*
 *
 *  Copyright 2015 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */

package com.zwl.swagger.plugins;

import com.zwl.swagger.CommentContainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

/**
 * 属性上的注释
 * @author zhangweilin
 * @Description:
 * @date 2021年08月20日 20:59
 */
@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER)
@Slf4j
public class ApiModelPropertyPropertyBuilderPlus implements ModelPropertyBuilderPlugin, ContextDescriper {
    private final DescriptionResolver descriptions;

    @Autowired
    CommentContainer commentContainer;

    @Autowired
    public ApiModelPropertyPropertyBuilderPlus(DescriptionResolver descriptions) {
        this.descriptions = descriptions;
    }

    @Override
    public void apply(ModelPropertyContext context) {
        String fieldsDescription = "";
        try {
            fieldsDescription = getFieldsDescription(context);
            String desc = commentContainer.getFieldCommentMap().get(fieldsDescription);
            context.getBuilder().description(desc).required(isRequired(desc));
        } catch (Exception e) {
            log.error("ApiModelPropertyPropertyBuilderPlus异常，fieldsDescription: " + fieldsDescription,e);
        }
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }
}
